package com.plian.system.controller.wbdsh;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.Func;
import com.plian.Tools.StringPool;
import com.plian.Tools.TokenUtil;
import com.plian.Tools.pagedata.PageData;
import com.plian.spring.SpringUtil;
import com.plian.system.annotation.LogOperation;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.Resubmit;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.dao.sys.user.UserDao;
import com.plian.system.entity.wbdsh.WbdsDailyThing;
import com.plian.system.entity.wbdsh.WbdsDailyThingHq;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.search.TokenSearch;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.properties.GzwProperties;
import com.plian.system.service.wbdsh.IWbdsDailyThingHqService;
import com.plian.system.vo.wbdsh.WbdsDailyThingHqVO;
import com.plian.system.wrapper.wbdsh.WbdsDailyThingHqWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 董事会会前报告
 * @author zhangsk
 * @create 2025-01-26 10:50
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("api/wbdsDailythingHq")
public class WbdsDailyThingHqController {

    private IWbdsDailyThingHqService iDailyThingHqService;

    private WbdsDailyThingHqWrapper dailyThingHqWrapper;

    private UserDao userDao;

    /**
     * 新增或修改
     */
    @PostMapping("/submit")
    @Resubmit(delaySeconds = 0)
    @LogOperation("外部董事会前报告-提交")
    public R submit(@Valid @RequestBody WbdsDailyThingHq dailyThingHq) {
        if (Optional.ofNullable(dailyThingHq.getStatus()).isPresent() &&
                dailyThingHq.getStatus() != FormStatusConstant.STASH){
            if (!iDailyThingHqService.checkIsExisted(dailyThingHq.getId(), dailyThingHq.getCode())){
                return new R(CustomCode.builder().message("单据编码已存在").code(1999).success(false).build());
            }
        }
        return iDailyThingHqService.submit(dailyThingHq) ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @LogOperation("外部董事会前报告-删除")
    public R remove(@RequestBody PageData pd) {
        List<String> ids = (List<String>)pd.get("ids");
        return iDailyThingHqService.deleteLogic(Func.toLongList(StringUtils.join(ids, StringPool.COMMA)))
                ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
    }

    /**
     * 详情
     */
    @PostMapping("/detail")
    public R<WbdsDailyThingHqVO> detail(@Valid @RequestBody WbdsDailyThingHq dailyThing) {
        WbdsDailyThingHq detail = iDailyThingHqService.getOne(Condition.getQueryWrapper(dailyThing));
        return R.data(dailyThingHqWrapper.entityToVO(detail));
    }

    /**
     * 分页
     */
    @PostMapping("/list")
    public ListResult<WbdsDailyThingHqVO> list(@RequestBody Query query) {
        List<SearchEntity> entityList = query.getSearch();
        if (query.getAscs()==null&&query.getDescs()==null){
            query.setDescs("create_time");
        }

        List<String> userIds = new ArrayList<>();
        Object userName = entityList.stream().filter(p -> "create_user_name".equals(p.getField())).findAny().orElse(new SearchEntity()).getValue();
        if (userName != null) {
            entityList.removeIf(p -> "create_user_name".equals(p.getField()));
            List<PageData> users;
            try {
                users = userDao.findByName(userName.toString());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            userIds = Optional.ofNullable(users).orElse(new ArrayList<>()).stream().map(p -> p.get("id").toString()).collect(Collectors.toList());
        }
        QueryWrapper<WbdsDailyThingHq> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new WbdsDailyThing()), entityList
        );
        if (userName != null) {
            if (CollectionUtil.isNotEmpty(userIds)) {
                queryWrapper.in("create_user", userIds);
            } else {
                queryWrapper.in("create_user", "");
            }
        }
        GzwProperties gzwProperties = SpringUtil.getBean(GzwProperties.class);
        String gzwOrgId = gzwProperties.getId();
        if (null != TokenUtil.getTokenOrgId() &&
                TokenUtil.getTokenOrgId().equals(gzwOrgId)){
            if(null == query.getFlag()) query.setFlag(1);
            TokenSearch<WbdsDailyThingHq> tokenSearch = new TokenSearch<>();
            tokenSearch.addTokenQuery(queryWrapper, query);
        }else {
            queryWrapper.lambda().eq(WbdsDailyThingHq::getCreateUser, TokenUtil.getTokenUserId());
        }
        IPage<WbdsDailyThingHq> pages = iDailyThingHqService.page(Condition.getPage(query), queryWrapper);
        List<WbdsDailyThingHqVO> dailyThingVOList = dailyThingHqWrapper.entityToVO(pages.getRecords());
        ListResult<WbdsDailyThingHqVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(dailyThingVOList);
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;
    }

}
